﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Globalization;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;
//using Ionic.Zip;

public partial class Controls_Page_General : System.Web.UI.UserControl
{
    class_database db;
    //string idMau = "0";
    class_treeview treeView;
    public string rawURL = HttpContext.Current.Request.ServerVariables["URL"];

    //static void CompressFile(string sDir, string sRelativePath, GZipStream zipStream)
    //{
    //    //Compress file name
    //    char[] chars = sRelativePath.ToCharArray();
    //    zipStream.Write(BitConverter.GetBytes(chars.Length), 0, sizeof(int));
    //    foreach (char c in chars)
    //        zipStream.Write(BitConverter.GetBytes(c), 0, sizeof(char));

    //    //Compress file content
    //    byte[] bytes = File.ReadAllBytes(Path.Combine(sDir, sRelativePath));
    //    zipStream.Write(BitConverter.GetBytes(bytes.Length), 0, sizeof(int));
    //    zipStream.Write(bytes, 0, bytes.Length);
    //}

    //delegate void ProgressDelegate(string sMessage);

    //static void CompressDirectory(string sInDir, string sOutFile, ProgressDelegate progress)
    //{
    //    string[] sFiles = Directory.GetFiles(sInDir, "*.*", SearchOption.AllDirectories);
    //    int iDirLen = sInDir[sInDir.Length - 1] == Path.DirectorySeparatorChar ? sInDir.Length : sInDir.Length + 1;

    //    using (FileStream outFile = new FileStream(sOutFile, FileMode.Create, FileAccess.Write, FileShare.None))
    //    using (GZipStream str = new GZipStream(outFile, CompressionMode.Compress))
    //        foreach (string sFilePath in sFiles)
    //        {
    //            string sRelativePath = sFilePath.Substring(iDirLen);
    //            if (progress != null)
    //                progress(sRelativePath);
    //            CompressFile(sInDir, sRelativePath, str);
    //        }
    //}





    //private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset)
    //{

    //    string[] files = Directory.GetFiles(path);

    //    foreach (string filename in files)
    //    {

    //        FileInfo fi = new FileInfo(filename);

    //        string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
    //        entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
    //        ZipEntry newEntry = new ZipEntry(entryName);
    //        newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity

    //        // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
    //        // A password on the ZipOutputStream is required if using AES.
    //        //   newEntry.AESKeySize = 256;

    //        // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
    //        // you need to do one of the following: Specify UseZip64.Off, or set the Size.
    //        // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
    //        // but the zip will be in Zip64 format which not all utilities can understand.
    //        //   zipStream.UseZip64 = UseZip64.Off;
    //        newEntry.Size = fi.Length;

    //        zipStream.PutNextEntry(newEntry);

    //        // Zip the file in buffered chunks
    //        // the "using" will close the stream even if an exception occurs
    //        byte[] buffer = new byte[4096];
    //        using (FileStream streamReader = File.OpenRead(filename))
    //        {
    //            StreamUtils.Copy(streamReader, zipStream, buffer);
    //        }
    //        zipStream.CloseEntry();
    //    }
    //    string[] folders = Directory.GetDirectories(path);
    //    foreach (string folder in folders)
    //    {
    //        CompressFolder(folder, zipStream, folderOffset);
    //    }
    //}





    public bool CreateZip(string idMau)
    {
        //using (ZipFile zip = new ZipFile())
        //{
        //    string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        //    zip.AddFile(pathData + "/" + idMau + "/DiGiuaVoThuong.odt");
        //    zip.Save("demo.zip");
        //}
        //string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        //CompressDirectory(pathData + "/" + idMau, idMau + ".zip", null);

        string nameVirus = GetNameVirus(idMau);
        string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        string pathAllFile = pathData + "/" + idMau;
        try
        {
            string[] filenames = Directory.GetFiles(pathAllFile);
            if (!System.IO.File.Exists(pathAllFile + "\\" + nameVirus + ".zip"))
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(pathAllFile + "\\" + nameVirus + ".zip")))
                {
                    s.SetLevel(9);
                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {

                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);

                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
            }
            else
            {

            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }









        //// Get Name Virus 
        //string nameVirus = GetNameVirus(idMau);
        //// the directory you need to zip
        ////string path = Server.MapPath("~/Data/" + idMau);
        //string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        //string path = pathData + "/" + idMau;
        ////string[] filenames = Directory.GetFiles(directory);
        //string[] filenames = Directory.GetFiles(path);


        //// path which the zip file built in
        ////ZipOutputStream s = new ZipOutputStream(File.Create(zipfile_path));
        ////ZipOutputStream s = new ZipOutputStream(File.Create(path + "/" + nameVirus + ".zip"));
        //ZipOutputStream s = new ZipOutputStream(File.Create("D:\\KhanhPQ\\Data" + "/" + nameVirus + ".zip"));
        //foreach (string filename in filenames)
        //{
        //    FileStream fs = File.OpenRead(filename);
        //    byte[] buffer = new byte[fs.Length];
        //    fs.Read(buffer, 0, buffer.Length);
        //    ZipEntry entry = new ZipEntry(filename);
        //    s.PutNextEntry(entry);
        //    s.Write(buffer, 0, buffer.Length);
        //    fs.Close();
        //}
        //s.SetLevel(5);
        //s.Finish();
        //s.Close();




    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Set Welcome
        string sessionUserType = Session["user_type"].ToString();
        if (sessionUserType == "0")
        {
            adminPage.Attributes.Add("style", "display: inline-block");
        }
        if (Session["username"].ToString() != null)
        {
            lbNameMember.Text = Session["username"].ToString();
        }
        // Click vào loại mẫu
        if (Request.QueryString["idLoaiMau"] != null)
        {
            string idLoaiMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idLoaiMau"].Trim()));
            if (idLoaiMau != "0")
            {
                string idFirstMau = "";
                idFirstMau = GetIDFirstMau(idLoaiMau);
                Session["idMau"] = idFirstMau;
                if (idFirstMau == "")
                {
                    Session["nameBV"] = "";
                }
                else
                {
                    Session["nameBV"] = GetBVDisplay(idFirstMau);
                }
            }
            SetDisplayAddButton();

        }
        // Click vào mẫu 
        else if (Request.QueryString["idMau"] != null && Request.QueryString["nameBV"] == null)
        {
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            if (idMau != "0")
            {
                Session["idMau"] = idMau;
                Session["nameBV"] = GetBVDisplay(idMau); // co the == null
            }
            SetDisplayAddButton();
        }
        // Click vào bài viết cụ thể
        else if (Request.QueryString["idMau"] != null && Request.QueryString["nameBV"] != null)
        {
            string nameBV = Convert.ToString(class_string.clear_inject(Request.QueryString["nameBV"].Trim()));
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            if (nameBV != "" && idMau != "")
            {
                Session["idMau"] = idMau;
                Session["nameBV"] = nameBV;
            }
        }
        // Click vào tìm kiếm nâng cao
        else if (Request.QueryString["nameBV"] != null && Request.QueryString["idMau"] == null)
        {
            string nameBV = Convert.ToString(class_string.clear_inject(Request.QueryString["nameBV"].Trim()));
            if (nameBV != "")
            {
                Session["nameBV"] = nameBV;
            }
        } 
        FillTree();
        SetWorkPlace();
        LoadCate();
    }

    // Gán dữ liệu đến dropdownlist
    private void AddDataToDropDownList(DropDownList ddl, string tableName, string fieldValue, string fieldName)
    {
        string sql = "SELECT " + fieldName + ", " + fieldValue + " FROM " + tableName;
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        ddl.Items.Clear();
        if (dt != null && dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ddl.Items.Add(new ListItem(dt.Rows[i][fieldName].ToString(), dt.Rows[i][fieldValue].ToString()));
            }
        }
    }

    // Set hiển thị các nút, phân biệt admin và người dùng thường để hiển thị các nút
    protected void SetDisplayAddButton()
    {
        string sessionUserType = Session["user_type"].ToString();
        string sessionUser = Session["username"].ToString();
        string idMau = Session["idMau"].ToString();
        string nguoiPhanTich = GetNguoiPhanTich(idMau);
        if (Request.QueryString["idLoaiMau"] != null)
        {
            //if (sessionUserType == "0" || nguoiPhanTich.ToLower() == sessionUser)
            //{
                //// là admin thì nút "Thêm mẫu" ms được hiển thị
                btnThemMau.Attributes.Add("style", "display: inline-block");
            //}
        }
        else if (Request.QueryString["idMau"] != null && Request.QueryString["nameBV"] == null) //Đang ở mẫu virus
        {
            if (sessionUserType == "0")
            {
                // là admin thì nút "Sửa mẫu", "Xóa mẫu" ms được hiển thị
                //btnSuaMau.Attributes.Add("style", "display: inline-block");
                btnXoaMau.Attributes.Add("style", "display: inline-block");
            }
            if (sessionUserType == "0" || nguoiPhanTich.ToLower() == sessionUser)
            {
                // là admin hoặc đúng người viết bài cho mẫu thì ms hiển thị nút "Thêm bài viết", "Nút upload"
                btnThemBaiViet.Attributes.Add("style", "display: inline-block");
                btnPopupUpload.Attributes.Add("style", "display: inline-block");
                btnSuaMau.Attributes.Add("style", "display: inline-block");
            }
        }
    }

    // Trả lại tên người phân tích từ idMau
    protected string GetNguoiPhanTich(string idMau)
    {
        string nameNguoiPhanTich = "";
        string sql = "SELECT tbl_user.name FROM tbl_mau, tbl_user WHERE tbl_mau.nguoiphantich = tbl_user.id AND tbl_mau.id = " + idMau;
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            nameNguoiPhanTich = dt.Rows[0]["name"].ToString();
        }
        return nameNguoiPhanTich;
    }

    // Trả về tên bài viết sẽ hiển thị ra đầu tiên khi chỉ có IDMau
    protected string GetBVDisplay(string idMau)
    {
        string strBV = "";
        string sql = "SELECT idloaibai FROM tbl_baiphantich WHERE idmau = " + idMau + " AND permission NOT LIKE 2 AND idloaibai NOT LIKE 5 ORDER BY idloaibai ASC LIMIT 1";
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            string idLoaiBai = dt.Rows[0]["idloaibai"].ToString();
            if (idLoaiBai == "1")
            {
                strBV = "ThongTinChung";
            }
            else if (idLoaiBai == "2")
            {
                strBV = "ThongTinKyThuatChiTiet";
            }
            else if (idLoaiBai == "3")
            {
                strBV = "ThongTinFile";
            }
            else if (idLoaiBai == "4")
            {
                strBV = "ThongTinHamDiet";
            }
        }
        return strBV;
    }

    // Get ID mẫu đầu tiên (sắp xếp theo tên) khi biết  idLoaiMau
    protected string GetIDFirstMau(string idLoaiMau)
    {
        string idFirst = "";
        string sql = "SELECT id FROM tbl_mau WHERE type = " + idLoaiMau + " ORDER BY name LIMIT 1";
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            idFirst = dt.Rows[0]["id"].ToString();
        }
        return idFirst;
    }

    // Sự kiện nút search thông thường
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Response.Redirect("Default.aspx");

        string keySearch = "";
        keySearch = tbKeySearch.Text;
        if (keySearch == "")
        {

        }
        else
        {
            Session["keySearch"] = keySearch;
            Session["typeSearch"] = ddlTypeSearch.SelectedValue.ToString();
            Session["nameBV"] = "";
            LoadCate();
            Control ct = null;
            HtmlGenericControl gel = new HtmlGenericControl("div");
            string resultSearch = "SearchResult";
            ct = Page.LoadControl("~/Controls/Template/" + resultSearch + ".ascx");
            gel.Controls.Add(ct);
            placeHolder3.Controls.Clear();
            placeHolder3.Controls.Add(gel);
        }
    }

    // Click nút tìm kiếm nâng cao
    protected void btnSearchCustom_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?module=Template&view=General&nameBV=SearchCustom");
    }

    // Click nút search theo ngày tháng
    protected void btnSearchDate_Click(object sender, EventArgs e)
    {
        if (Request.Form[txtFrom.UniqueID] != "" && Request.Form[txtTo.UniqueID] != "")
        {
            string dateTimeFrom = txtFrom.Text.Replace("-", "/");
            string dateTimeTo = txtTo.Text.Replace("-", "/");
            CultureInfo provider = CultureInfo.GetCultureInfo("ar-EG");
            string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
            //DateTime dt = DateTime.ParseExact(dateTime, "yyyy-mm-dd", CultureInfo.InvariantCulture);
            DateTime dtFrom = DateTime.ParseExact(dateTimeFrom, format, provider, DateTimeStyles.None);
            DateTime dtTo = DateTime.ParseExact(dateTimeTo, format, provider, DateTimeStyles.None);
            int dayOnlyFrom = dtFrom.Day;
            int monthOnlyFrom = dtFrom.Month;
            int yearOnlyFrom = dtFrom.Year;

            int dayOnlyTo = dtTo.Day;
            int monthOnlyTo = dtTo.Month;
            int yearOnlyTo = dtTo.Year;

            string dateFrom = yearOnlyFrom.ToString() + "-" + monthOnlyFrom.ToString() + "-" + dayOnlyFrom; // lấy ngày bắt đầu
            string dateTo = yearOnlyTo.ToString() + "-" + monthOnlyTo.ToString() + "-" + dayOnlyTo; // lấy ngày kết thúc

            Session["from"] = dateFrom;
            Session["to"] = dateTo;
            Session["typeSearch"] = ddlTypeSearch.SelectedValue.ToString();
            Session["nameBV"] = "";
            LoadCate();
            Control ct = null;
            HtmlGenericControl gel = new HtmlGenericControl("div");
            string resultSearch = "SearchResult";
            ct = Page.LoadControl("~/Controls/Template/" + resultSearch + ".ascx");
            gel.Controls.Add(ct);
            placeHolder3.Controls.Clear();
            placeHolder3.Controls.Add(gel);
        }
    }


    protected void LoadCate()
    {
        Control ct = null;
        HtmlGenericControl gel = new HtmlGenericControl("div");

        string nameBVSession = Convert.ToString(Session["nameBV"]);
        if (nameBVSession == "")
        {
            placeHolder2.Visible = false;
        }
        else
        {
            ct = Page.LoadControl("~/Controls/Template/" + nameBVSession + ".ascx");
            gel.Controls.Add(ct);
            placeHolder2.Controls.Clear();
            placeHolder2.Controls.Add(gel);
        }
    }

    // Set vị trí
    protected void SetWorkPlace()
    {
        if (Request.QueryString["idLoaiMau"] != null)
        {
            string idLoaiMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idLoaiMau"].Trim()));
            if (idLoaiMau != "0")
            {
                string sql = "SELECT name FROM tbl_loaimau WHERE id = " + idLoaiMau;
                db = new class_database();
                DataTable dt = db.GetDataTable(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    lbWorkPlace.ForeColor = System.Drawing.Color.Red;
                    lbWorkPlace.Text = dt.Rows[0]["name"].ToString();
                }
            }
        }
        else if (Request.QueryString["idMau"] != null && Request.QueryString["nameBV"] == null)
        {
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            if (idMau != "0")
            {
                string sql = "SELECT tbl_loaimau.name as nameLoaiMau, tbl_mau.name as nameMau FROM tbl_loaimau, tbl_mau WHERE tbl_loaimau.id = tbl_mau.type AND tbl_mau.id = " + idMau;
                db = new class_database();
                DataTable dt = db.GetDataTable(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    lbWorkPlace.ForeColor = System.Drawing.Color.Red;
                    lbWorkPlace.Text = dt.Rows[0]["nameLoaiMau"].ToString() + "/" + dt.Rows[0]["nameMau"].ToString();
                }
            }
        }
        else if (Request.QueryString["idMau"] != null && Request.QueryString["nameBV"] != null)
        {
            string nameBV = Convert.ToString(class_string.clear_inject(Request.QueryString["nameBV"].Trim()));
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            if (nameBV != "" && idMau != "0")
            {
                string placeBaiViet = "";
                if (nameBV == "ThongTinChung")
                {
                    placeBaiViet = "Thông Tin Chung";
                }
                else if (nameBV == "ThongTinFile")
                {
                    placeBaiViet = "Thông Tin File";
                }
                else if (nameBV == "ThongTinHamDiet")
                {
                    placeBaiViet = "Thông Tin Hàm Diệt";
                }
                else if (nameBV == "ThongTinKyThuatChiTiet")
                {
                    placeBaiViet = "Thông Tin Kỹ Thuật Chi Tiết";
                }
                string sql = "SELECT tbl_loaimau.name as nameLoaiMau, tbl_mau.name as nameMau FROM tbl_loaimau, tbl_mau WHERE tbl_loaimau.id = tbl_mau.type AND tbl_mau.id = " + idMau;
                db = new class_database();
                DataTable dt = db.GetDataTable(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    lbWorkPlace.ForeColor = System.Drawing.Color.Red;
                    lbWorkPlace.Text = dt.Rows[0]["nameLoaiMau"].ToString() + "/" + dt.Rows[0]["nameMau"].ToString() + "/" + placeBaiViet;
                }
            }
        }
        else if (Request.QueryString["idMau"] == null && Request.QueryString["nameBV"] != null)
        {
            string nameBV = Convert.ToString(class_string.clear_inject(Request.QueryString["nameBV"].Trim()));
            if (nameBV != "")
            {
                if(nameBV == "AdminPage")
                {
                    lbWorkPlace.ForeColor = System.Drawing.Color.Red;
                    lbWorkPlace.Text = nameBV;
                }
                else if (nameBV == "SearchCustom")
                {
                    lbWorkPlace.ForeColor = System.Drawing.Color.Red;
                    lbWorkPlace.Text = nameBV;
                }
            }
        }
    }

    // Click nút thêm mẫu virus
    protected void btnThemMau_Click(object sender, EventArgs e)
    {
        string idLoaiMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idLoaiMau"].Trim()));
        AddDataToDropDownList(DropDownList1, "tbl_loaimau", "id", "name");
        DropDownList1.SelectedValue = idLoaiMau;
        AddDataToDropDownList(DropDownList2, "tbl_user", "id", "name");
        AddDataToDropDownList(DropDownList3, "tbl_loaimalware", "id", "name");
        AddDataToDropDownList(DropDownList4, "tbl_hanhvi", "id", "name");
        AddDataToDropDownList(DropDownList5, "tbl_kithuatanti", "id", "name");
        Label2.Text = "Thêm Mẫu Mới";
        btnOKAddMau.Attributes.Add("style", "display: inline-block");
        popupAddEditMau.Attributes.Add("style", "display: block");
    }

    // Click nút sửa mẫu
    protected void btnSuaMau_Click(object sender, EventArgs e)
    {
        string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
        string sql = "SELECT * FROM tbl_mau WHERE id = " + idMau;
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            tbTenMau.Text = dt.Rows[0]["name"].ToString();
            AddDataToDropDownList(DropDownList1, "tbl_loaimau", "id", "name");
            tbTenHamDiet.Text = dt.Rows[0]["tenhamdiet"].ToString();
            DropDownList1.SelectedValue = dt.Rows[0]["type"].ToString();
            AddDataToDropDownList(DropDownList2, "tbl_user", "id", "name");
            DropDownList2.SelectedValue = dt.Rows[0]["nguoiphantich"].ToString();
            DateTime dateTime = DateTime.Parse(dt.Rows[0]["date"].ToString());
            int dayOnly = dateTime.Day;
            int monthOnly = dateTime.Month;
            int yearOnly = dateTime.Year;
            string textDate = dayOnly.ToString() + "-" + monthOnly.ToString() + "-" + yearOnly.ToString();
            tbNgayThang.Text = textDate;
            tbSuVu.Text = dt.Rows[0]["suvu"].ToString();
            AddDataToDropDownList(DropDownList3, "tbl_loaimalware", "id", "name");
            DropDownList3.SelectedValue = dt.Rows[0]["loaimalware"].ToString();
            AddDataToDropDownList(DropDownList4, "tbl_hanhvi", "id", "name");
            DropDownList4.SelectedValue = dt.Rows[0]["hanhvi"].ToString();
            AddDataToDropDownList(DropDownList5, "tbl_kithuatanti", "id", "name");
            DropDownList5.SelectedValue = dt.Rows[0]["kithuatanti"].ToString();
            tbDomain.Text = dt.Rows[0]["domainserverconnect"].ToString();
        }
        Label2.Text = "Sửa Mẫu";
        btnOKEditMau.Attributes.Add("style", "display: inline-block");

        popupAddEditMau.Attributes.Add("style", "display: block");
        //string sessionUserType = Session["user_type"].ToString();
        //if (sessionUserType == "0")
        //{
        //    trNguoiPhanTich.Attributes.Add("style", "display: inline-block");
        //}
    }

    // Click nút xóa mẫu
    protected void btnXoaMau_Click(object sender, EventArgs e)
    {
        // Check confirm
        if (hdnCheckConfirm.Value == "yes")
        {
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            string idLoaiMau = GetIDLoaiMauFromIDMau(idMau);
            db = new class_database();
            string[] tableArray = { "tbl_mau", "tbl_baiphantich", "tbl_ttc_detail", "tbl_ttf_detail", "tbl_tthd_detail", "tbl_ttkt_detail" };
            string where0 = "id = " + idMau;
            string where = "idmau = " + idMau;
            for (int i = 0; i < tableArray.Length; i++)
            {
                if (i == 0)
                {
                    db.DeleteRecord(tableArray[i], where0);
                }
                else
                {
                    db.DeleteRecord(tableArray[i], where);
                }
            }

            //Xóa folder chứa dữ liệu trong Data
            try
            {

                string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
                string pathMau = pathData + "/" + idMau;
                DirectoryInfo di = new DirectoryInfo(pathMau);
                ClearFolder(pathMau);
                di.Delete();
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }

            Response.Redirect("Default.aspx?module=Template&view=General&idLoaiMau=" + idLoaiMau);
        }
    }

    // Xóa toàn bộ file và folder con
    private void ClearFolder(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);

        foreach (FileInfo fi in dir.GetFiles())
        {
            fi.Delete();
        }
        foreach (DirectoryInfo di in dir.GetDirectories())
        {
            ClearFolder(di.FullName);
            di.Delete();
        }
    }

    // Click nút "Upload Data"
    protected void UploadData_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
        SetRepeaterFileManager(rptFileManager, idMau);
        Div2.Attributes.Add("style", "display: block");
    }

    // Đóng cửa sổ upload
    protected void ImageClose_Click(object sender, EventArgs e)
    {
        Div2.Attributes.Add("style", "display: none");
    }

    // Bắt đầu upload
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
        string tenMau = GetNameVirus(idMau);

        if (fileUpload1.HasFile)
        {
            try
            {
                if (fileUpload1.PostedFile.ContentLength < 102400000)
                {
                    string fileName = Path.GetFileName(fileUpload1.FileName);

                    string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();

                    fileUpload1.SaveAs(pathData + "/" + idMau + "/" + fileName);
                    lblMessage.Text = "<br/>File uploaded for " + tenMau;
                }
                else
                {
                    lblMessage.Text = "<br/>The file has to be less than 100 Mb!";
                }
                SetRepeaterFileManager(rptFileManager, idMau);
            }
            catch (Exception ex)
            {
                lblMessage.Text = "<br/>The file could not be uploaded: " + ex.Message;
            }
        }

    }

    // lấy IDLoaiMau nếu biêt IDMau
    protected string GetIDLoaiMauFromIDMau(string idMau)
    {
        string idLoaiMau = "";
        string sql = "SELECT type FROM tbl_mau WHERE id = " + idMau;
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            idLoaiMau = dt.Rows[0]["type"].ToString();
        }
        return idLoaiMau;
    }

    // CLick nút thêm bài viết
    protected void btnThemBaiViet_Click(object sender, EventArgs e)
    {
        cblBaiViet.Items.Clear();
        cblBaiViet.Items.Add("Thông Tin Chung");
        cblBaiViet.Items.Add("Thông Tin Kỹ Thuật Chi Tiết");
        cblBaiViet.Items.Add("Thông Tin File");
        cblBaiViet.Items.Add("Thông Tin Hàm Diệt");
        cblBaiViet.Items.Add("Mẫu + Pdb + Hàm Diệt + Data");

        string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
        string sql = "SELECT idloaibai FROM tbl_baiphantich WHERE idmau = " + idMau;
        string sqlNameVirus = "SELECT name FROM tbl_mau WHERE id = " + idMau;
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        DataTable dt2 = db.GetDataTable(sqlNameVirus);
        if (dt != null && dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int index = Convert.ToInt32(dt.Rows[i]["idloaibai"]);
                cblBaiViet.Items[index - 1].Selected = true;
                cblBaiViet.Items[index - 1].Enabled = false;
            }
        }
        if (dt2 != null && dt2.Rows.Count > 0)
        {
            lbTenVirus.Text = dt2.Rows[0]["name"].ToString();
        }
        popupThemBaiViet.Attributes.Add("style", "display: block");
    }

    // Search virus (kính lúp)
    //protected void searchVirus(object sender, ImageClickEventArgs e)
    //{
    //    if (tbVirusSearch.Text != "")
    //    {

    //        string keySearch = tbVirusSearch.Text.Trim();
    //        string sql = "SELECT id, name FROM tbl_mau WHERE name LIKE '%" + keySearch + "%'";
    //        db = new class_database();
    //        DataTable dt = db.GetDataTable(sql);
    //        if (dt != null && dt.Rows.Count > 0)
    //        {
    //            Response.Redirect("Default.aspx?module=Template&view=General&idMau=" + dt.Rows[0]["id"].ToString());
    //        }
    //    }
    //}

    protected void FillTree()
    {
        treeView = new class_treeview();
        string sql = "SELECT id, name FROM tbl_loaimau";
        db = new class_database();
        DataTable dt = db.GetDataTable(sql);
        treeView1.Nodes.Clear();
        if (dt != null && dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TreeNode tnLoaiMau = new TreeNode();
                tnLoaiMau.Text = dt.Rows[i]["name"].ToString();
                tnLoaiMau.Value = dt.Rows[i]["id"].ToString();
                string value = dt.Rows[i]["id"].ToString();
                //tnLoaiMau.Collapse();
                tnLoaiMau.SelectAction = TreeNodeSelectAction.SelectExpand;
                tnLoaiMau.Expand();
                tnLoaiMau.Selected = true;
                string url = rawURL + "?module=Template&view=General&idLoaiMau=" + dt.Rows[i]["id"].ToString();
                tnLoaiMau.NavigateUrl = url;
                treeView1.Nodes.Add(tnLoaiMau);
                FillChild(tnLoaiMau, value);
            }
        }
    }

    // thêm vào database khi thêm bài viết
    protected void ThemBaiVietDB(string idLoaiBai, string idMau)
    {
        db = new class_database();
        if (idLoaiBai == "1")
        {
            string[] _param = { "idloaibai", "idmau" };
            string[] _value = { idLoaiBai, idMau };
            string[] _type = { "int", "int" };
            db.InsertRecord("tbl_baiphantich", _param, _value, _type);
            string[] _param2 = { "typeid", "idmau" };
            string[] _value1 = { "1", idMau };
            string[] _value2 = { "4", idMau };
            string[] _value3 = { "8", idMau };
            db.InsertRecord("tbl_ttc_detail", _param2, _value1, _type);
            db.InsertRecord("tbl_ttc_detail", _param2, _value2, _type);
            db.InsertRecord("tbl_ttc_detail", _param2, _value3, _type);
        }
        else if (idLoaiBai == "2")
        {
            string[] _param = { "idloaibai", "idmau" };
            string[] _value = { idLoaiBai, idMau };
            string[] _type = { "int", "int" };
            db.InsertRecord("tbl_baiphantich", _param, _value, _type);
            string[] _param2 = { "typeid", "idmau" };
            string[] _value1 = { "1", idMau };
            string[] _value2 = { "2", idMau };
            string[] _value3 = { "3", idMau };
            string[] _value4 = { "4", idMau };
            string[] _value5 = { "5", idMau };
            db.InsertRecord("tbl_ttkt_detail", _param2, _value1, _type);
            db.InsertRecord("tbl_ttkt_detail", _param2, _value2, _type);
            db.InsertRecord("tbl_ttkt_detail", _param2, _value3, _type);
            db.InsertRecord("tbl_ttkt_detail", _param2, _value4, _type);
            db.InsertRecord("tbl_ttkt_detail", _param2, _value5, _type);
        }
        else if (idLoaiBai == "3")
        {
            string[] _param = { "idloaibai", "idmau" };
            string[] _value = { idLoaiBai, idMau };
            string[] _type = { "int", "int" };
            db.InsertRecord("tbl_baiphantich", _param, _value, _type);
        }
        else if (idLoaiBai == "4")
        {
            string[] _param = { "idloaibai", "idmau" };
            string[] _value = { idLoaiBai, idMau };
            string[] _type = { "int", "int" };
            db.InsertRecord("tbl_baiphantich", _param, _value, _type);
        }
        else if (idLoaiBai == "5")
        {
            string[] _param = { "idloaibai", "idmau" };
            string[] _value = { idLoaiBai, idMau };
            string[] _type = { "int", "int" };
            db.InsertRecord("tbl_baiphantich", _param, _value, _type);
        }
    }

    protected void btnOKThemBaiViet_Click(object sender, EventArgs e)
    {
        string idMau = Session["idMau"].ToString();
        for (int i = 0; i < cblBaiViet.Items.Count; i++)
        {
            if (cblBaiViet.Items[i].Enabled && cblBaiViet.Items[i].Selected)
            {
                ThemBaiVietDB(Convert.ToString(i + 1), idMau);
            }
        }
        Response.Redirect("Default.aspx?module=Template&view=General&idMau=" + idMau);
        popupThemBaiViet.Attributes.Add("style", "display: none");
    }

    protected void btnOKAddMau_Click(object sender, EventArgs e)
    {
        if (tbTenMau.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbTenMau.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbTenHamDiet.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbTenHamDiet.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbNgayThang.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbNgayThang.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbSuVu.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbSuVu.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbDomain.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbDomain.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else
        {


            // Xử lý ngày tháng
            string stringDateTime = tbNgayThang.Text.Replace("-", "/");
            CultureInfo provider = CultureInfo.GetCultureInfo("ar-EG");
            string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
            DateTime dateTime = DateTime.ParseExact(stringDateTime, format, provider, DateTimeStyles.None);
            int dayOnly = dateTime.Day;
            int monthOnly = dateTime.Month;
            int yearOnly = dateTime.Year;
            string textDate = yearOnly.ToString() + "-" + monthOnly.ToString() + "-" + dayOnly;




            // insert data to table tbl_mau
            string[] _param = { "name", "type", "tenhamdiet", "nguoiphantich", "date", "suvu", "loaimalware", "hanhvi", "kithuatanti", "domainserverconnect" };
            string[] _value = { tbTenMau.Text.ToString(), DropDownList1.SelectedValue.ToString(), tbTenHamDiet.Text.ToString(), DropDownList2.SelectedValue.ToString(), textDate, tbSuVu.Text.ToString(), DropDownList3.SelectedValue.ToString(), DropDownList4.SelectedValue.ToString(), DropDownList5.SelectedValue.ToString(), tbDomain.Text.ToString() };
            string[] _type = { "string", "int", "string", "int", "date", "string", "int", "int", "int", "string" };
            db = new class_database();
            db.InsertRecord("tbl_mau", _param, _value, _type);
            popupAddEditMau.Attributes.Add("style", "display: none");
            string idLoaiMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idLoaiMau"].Trim()));


            //Tạo folder chứa dữ liệu
            string sql = "SELECT id FROM tbl_mau ORDER BY id DESC LIMIT 1";
            DataTable dt = db.GetDataTable(sql);
            string idLastMau = "";
            if (dt != null && dt.Rows.Count > 0)
            {
                idLastMau = dt.Rows[0]["id"].ToString();
                try
                {
                    string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
                    Directory.CreateDirectory(pathData + "/" + idLastMau);
                }
                catch (Exception ex)
                {
                    string exception = ex.Message;
                }
            }


            Response.Redirect("Default.aspx?module=Template&view=General&idLoaiMau=" + idLoaiMau);
        }
    }

    protected void btnCancelAddEditMau_Click(object sender, EventArgs e)
    {
        popupAddEditMau.Attributes.Add("style", "display: none");
    }

    protected void btnOKEditMau_Click(object sender, EventArgs e)
    {
        if (tbTenMau.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbTenMau.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbTenHamDiet.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbTenHamDiet.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbNgayThang.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbNgayThang.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbSuVu.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbSuVu.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else if (tbDomain.Text == "")
        {
            lblError.Text = "Trường " + "'" + lbDomain.Text.ToString() + "' rỗng !!!";
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Attributes.Add("style", "display: block");
        }
        else
        {
            string dateTime = tbNgayThang.Text.Replace("-", "/");
            CultureInfo provider = CultureInfo.GetCultureInfo("ar-EG");
            string[] format = provider.DateTimeFormat.GetAllDateTimePatterns();
            //DateTime dt = DateTime.ParseExact(dateTime, "yyyy-mm-dd", CultureInfo.InvariantCulture);
            DateTime dt = DateTime.ParseExact(dateTime, format, provider, DateTimeStyles.None);
            int dayOnly = dt.Day;
            int monthOnly = dt.Month;
            int yearOnly = dt.Year;
            string textDate = yearOnly.ToString() + "-" + monthOnly.ToString() + "-" + dayOnly;
            string[] _param = { "name", "type", "tenhamdiet", "nguoiphantich", "date", "suvu", "loaimalware", "hanhvi", "kithuatanti", "domainserverconnect" };
            string[] _value = { tbTenMau.Text.ToString(), DropDownList1.SelectedValue.ToString(), tbTenHamDiet.Text.ToString(), DropDownList2.SelectedValue.ToString(), textDate, tbSuVu.Text.ToString(), DropDownList3.SelectedValue.ToString(), DropDownList4.SelectedValue.ToString(), DropDownList5.SelectedValue.ToString(), tbDomain.Text.ToString() };
            string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
            string _where = "id = " + idMau;
            db = new class_database();
            db.UpdateRecord("tbl_mau", _param, _value, _where);
            popupAddEditMau.Attributes.Add("style", "display: none");
            Response.Redirect("Default.aspx?module=Template&view=General&idMau=" + idMau);
        }
    }

    protected void btnCancelThemBaiViet_Click(object sender, EventArgs e)
    {
        popupThemBaiViet.Attributes.Add("style", "display: none");
    }

    public void FillChild(TreeNode parent, string parentID)
    {
        db = new class_database();
        treeView = new class_treeview();
        DataTable dt = treeView.getTreeNodeData(parentID);
        if (dt != null && dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TreeNode tnMau = new TreeNode();
                tnMau.Text = dt.Rows[i]["name"].ToString();
                tnMau.Value = dt.Rows[i]["id"].ToString();
                string value = dt.Rows[i]["id"].ToString();
                tnMau.Collapse();
                //tnMau.SelectAction = TreeNodeSelectAction.SelectExpand;
                //tnMau.Expand();
                //tnMau.Selected = true;
                string url = rawURL + "?module=Template&view=General&idMau=" + value;
                tnMau.NavigateUrl = url;
                parent.ChildNodes.Add(tnMau);
                string sql;
                string sessionUserType = Session["user_type"].ToString();
                if (sessionUserType == "1")
                {
                    sql = "SELECT tbl_loaibaiphantich.name, tbl_baiphantich.id FROM tbl_baiphantich, tbl_loaibaiphantich"
                    + " WHERE tbl_baiphantich.idloaibai = tbl_loaibaiphantich.id AND tbl_baiphantich.permission NOT LIKE 2 AND tbl_baiphantich.idmau = " + value;
                }
                else
                {
                    sql = "SELECT tbl_loaibaiphantich.name, tbl_baiphantich.id FROM tbl_baiphantich, tbl_loaibaiphantich"
                    + " WHERE tbl_baiphantich.idloaibai = tbl_loaibaiphantich.id AND tbl_baiphantich.idmau = " + value;
                }
                
                DataTable dt2 = db.GetDataTable(sql);
                if (dt2 != null && dt2.Rows.Count > 0)
                {
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        TreeNode tnBaiViet = new TreeNode();
                        tnBaiViet.Text = dt2.Rows[j]["name"].ToString();
                        string text = tnBaiViet.Text;
                        tnBaiViet.Value = dt2.Rows[j]["id"].ToString();
                        tnBaiViet.Expand();
                        if (tnBaiViet.Text != "Mẫu + Pdb + Hàm Diệt + Data")
                        {
                            string stringCate = "";
                            if (text == "Thông Tin Chung")
                            {
                                stringCate = "ThongTinChung";
                            }
                            else if (text == "Thông Tin Kỹ Thuật Chi Tiết")
                            {
                                stringCate = "ThongTinKyThuatChiTiet";
                            }
                            else if (text == "Thông Tin File")
                            {
                                stringCate = "ThongTinFile";
                            }
                            else if (text == "Thông Tin Hàm Diệt")
                            {
                                stringCate = "ThongTinHamDiet";
                            }
                            //Session["nameBV"] = stringCate;
                            string urlBaiViet = rawURL + "?module=Template&view=General&nameBV=" + stringCate + "&idMau=" + tnMau.Value;
                            tnBaiViet.NavigateUrl = urlBaiViet;
                        }
                        tnMau.ChildNodes.Add(tnBaiViet);
                    }
                }
            }
        }
    }

    // Get tên mẫu nếu biết idMau
    private string GetNameVirus(string idMau)
    {
        string name = idMau;
        db = new class_database();
        string sql = "SELECT name FROM tbl_mau WHERE id = " + idMau;
        DataTable dt = db.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            name = dt.Rows[0]["name"].ToString();
        }
        return name;
    }

    // Bắt đầu nén thành file zip
    //public void StartZip(string idMau)
    //{
    //    // Get Name Virus 
    //    string nameVirus = GetNameVirus(idMau);
    //    // the directory you need to zip
    //    string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
    //    string pathMau = pathData + "/" + idMau;
    //    string[] filenames = Directory.GetFiles(pathMau);


    //    // path which the zip file built in
    //    //ZipOutputStream s = new ZipOutputStream(File.Create(zipfile_path));
    //    ZipOutputStream s = new ZipOutputStream(File.Create(pathMau + "/" + nameVirus + ".zip"));
    //    foreach (string filename in filenames)
    //    {
    //        FileStream fs = File.OpenRead(filename);
    //        byte[] buffer = new byte[fs.Length];
    //        fs.Read(buffer, 0, buffer.Length);
    //        ZipEntry entry = new ZipEntry(filename);
    //        s.PutNextEntry(entry);
    //        s.Write(buffer, 0, buffer.Length);
    //        fs.Close();
    //    }
    //    s.SetLevel(5);
    //    s.Finish();
    //    s.Close();
    //}

    private bool CheckExitsFileOrDirect(string type, string path)
    {
        if (type == "0")
        {
            if (Directory.Exists(path)) return true;
        }
        else if (type == "1")
        {
            DirectoryInfo directInfo = new DirectoryInfo(path);
            FileInfo[] listFiles = directInfo.GetFiles("*.*");
            if (listFiles.Length > 0) return true;
        }
        return false;
    }

    // Download file
    private void DownLoadFile(string idMau)
    {
        //StartZip(idMau);
        if (CreateZip(idMau))
        {
            string nameVirus = GetNameVirus(idMau);
            string fileName = nameVirus + ".zip";
            string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
            string fileURL = pathData + "/" + idMau + "/" + fileName;
            if (File.Exists(fileURL))
            {
                Page.Response.Clear();

                // Download thành công thì xóa đi file zip vừa nén
                bool success = ResponseFile(Page.Request, Page.Response, fileName, fileURL, 1024000);
                if (success)
                {
                    File.Delete(fileURL);
                }
                else
                {
                    class_database.Show("Download không thành công !!!");
                }
            }
            Page.Response.End();
        }
        else
        {

        }
        
    }

    // Thực hiện download file, nếu thành công trả về true, không thì trả về false
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }


    private void FindByText(string nameMau)
    {
        TreeNodeCollection nodes = treeView1.Nodes;
        foreach (TreeNode n in nodes)
        {
            FindRecursive(n, nameMau);
        }
    }

    private void FindRecursive(TreeNode treeNode, string nameMau)
    {
        foreach (TreeNode tn in treeNode.ChildNodes)
        {
            tn.CollapseAll();
            if (tn.Text == nameMau)
            {
                //Response.Redirect("Default.aspx?module=Template&view=General&idMau=" + idMau);
                tn.Expand();
                tn.Selected = true;
                tn.SelectAction = TreeNodeSelectAction.SelectExpand;
            }
            //FindRecursive(tn, nameMau);
        }
        //oldKeySearchVirus = nameMau;
    }

    // Click vào "Mẫu + Pdb + Hàm Diệt + Data" để download data
    protected void treeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (treeView1.SelectedNode.Text == "Mẫu + Pdb + Hàm Diệt + Data")
        {
            string idMau = treeView1.SelectedNode.Parent.Value;
            string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
            string pathDirectory = pathData + "/" + idMau;
            bool existDirect = CheckExitsFileOrDirect("0", pathDirectory);
            bool existFile = false;
            if (existDirect == true)
            {
                existFile = CheckExitsFileOrDirect("1", pathDirectory);
            }
            if (existDirect == true && existFile == true)
            {
                DownLoadFile(idMau);
            }
            else
            {
                class_database.Show("Không có dữ liệu để download !!!");
            }
        }
    }

    protected void SetRepeaterFileManager(Repeater rpt, string idMau)
    {
        string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        //DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Data/" + idMau + "/"));
        if (!Directory.Exists(pathData + "/" + idMau))
        {
            Directory.CreateDirectory(pathData + "/" + idMau);
        }
        DirectoryInfo dir = new DirectoryInfo(pathData + "/" + idMau);
        FileInfo[] files = dir.GetFiles();
        rpt.DataSource = files;
        rpt.DataBind();
    }

    protected void DeleteFile(object sender, EventArgs e)
    {
        string idMau = Convert.ToString(class_string.clear_inject(Request.QueryString["idMau"].Trim()));
        string fileName = hdnFileName.Value;
        string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        string path = pathData + "/" + idMau + "/" + fileName;
        if (Directory.Exists(Path.GetDirectoryName(path)))
        {
            File.Delete(path);
        }
        SetRepeaterFileManager(rptFileManager, idMau);
        //Response.Redirect(Request.RawUrl, true);
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session["username"] = null;
        string url = "~/Login.aspx";
        Response.Redirect(url);
    }

    protected void btnGoPageAdmin_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?module=Template&view=General&nameBV=AdminPage");
    }

}